package com.example.demo.config.aspect;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;

 /**
 　　* @description:
 　　* @author haitao.li
 　　* @date 2020/12/16 17:36
 　　*/
@Aspect
@Component
@Order(2)
public class BindingResultAspect {


    @Pointcut("execution(public * com.example.demo.controller.*.*(..))")
    public void BindingResult() {
    }

    @Around("BindingResult()")
    public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {
        Object[] args = joinPoint.getArgs();
        for (Object arg : args) {
            if (arg instanceof BindingResult) {
                BindingResult result = (BindingResult) arg;
                if (result.hasErrors()) {
                    FieldError fieldError = result.getFieldError();
                    if(fieldError!=null){
                        return fieldError.getDefaultMessage();
                    }else{
                        return fieldError.getDefaultMessage();
                    }
                }
            }
        }
        return joinPoint.proceed();
    }
}
